package com.se.common;

import java.sql.Timestamp;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

/**
 * <p>
 * <code>DateUtil</code>?? Date?? Time?? ??o? class???. ????? ??????? ???α?????? ????? ?? ??? class???? ??￥?? ??o? ???? ?????? ?????? ???? ??????
 * GregorianCalendar?? Calendar class?? ?????? ?????.
 * <p>
 * <strong>Time Format Syntax:</strong>
 * <p>
 * <em>time pattern</em> string?? ?????? time format?? ?????. pattern?? ?????? ???? define??? ???: <blockquote>
 *
 * <pre>
 *  Symbol   Meaning                 Presentation        Example
 *  ------   -------                 ------------        -------
 *  G        era designator          (Text)              AD
 *  y        year                    (Number)            1996
 *  M        month in year           (Text &amp; Number)     July &amp; 07
 *  d        day in month            (Number)            10
 *  h        hour in am/pm (1&tilde;12)    (Number)            12
 *  H        hour in day (0&tilde;23)      (Number)            0
 *  m        minute in hour          (Number)            30
 *  s        second in minute        (Number)            55
 *  S        millisecond             (Number)            978
 *  E        day in week             (Text)              Tuesday
 *  D        day in year             (Number)            189
 *  F        day of week in month    (Number)            2 (2nd Wed in July)
 *  w        week in year            (Number)            27
 *  W        week in month           (Number)            2
 *  a        am/pm marker            (Text)              PM
 *  k        hour in day (1&tilde;24)      (Number)            24
 *  K        hour in am/pm (0&tilde;11)    (Number)            0
 *  z        time zone               (Text)              Pacific Standard Time
 *  '        escape for text         (Delimiter)
 *  ''       single quote            (Literal)           '
 * </pre>
 *
 * </blockquote>
 * <p>
 * <strong>Examples Using the US Locale:</strong> <blockquote>
 *
 * <pre>
 *  Format Pattern                         Result
 *  --------------                         -------
 *  &quot;yyyy.MM.dd G 'at' HH:mm:ss z&quot;    -&gt;&gt;  1996.07.10 AD at 15:08:56 PDT
 *  &quot;EEE, MMM d, ''yy&quot;                -&gt;&gt;  Wed, July 10, '96
 *  &quot;h:mm a&quot;                          -&gt;&gt;  12:08 PM
 *  &quot;hh 'o''clock' a, zzzz&quot;           -&gt;&gt;  12 o'clock PM, Pacific Daylight Time
 *  &quot;K:mm a, z&quot;                       -&gt;&gt;  0:00 PM, PST
 *  &quot;yyyyy.MMMMM.dd GGG hh:mm aaa&quot;    -&gt;&gt;  1996.July.10 AD 12:08 PM
 * </pre>
 *
 * </blockquote>
 * <p>
 * <strong>Code Sample:</strong> <blockquote>
 *
 * <pre>
 * DateUtil.compareDate(&quot;2002-10-02&quot;, &quot;2002-10-01&quot;, &quot;yyyy-MM-dd&quot;); // ?? ??￥?? ?? --&gt; 1 ?? return
 * DateUtil.compareDate(&quot;23:52:12&quot;, &quot;23:52:12&quot;, &quot;HH:mm:ss&quot;); // ?? ?ð??? ?? --&gt; 0 ?? return
 * int diff = DateUtil.daysDiff(&quot;2002-10-02&quot;, &quot;2002-10-03&quot;, &quot;yyyy-MM-dd&quot;); // ?? ??￥?? ??????? ???
 * String dateString4 = DateUtil.formatCalendar(cal, &quot;yyyy-MM-dd&quot;); // Calendar --&gt; String
 * String dateString3 = DateUtil.formatDate(date, &quot;yyyy-MM-dd&quot;); // Date --&gt; String
 * String dateString1 = DateUtil.getTime(&quot;yyyy-MM-dd&quot;); // ??￥?? ??? format
 * String dateString2 = DateUtil.getTime(&quot;yyyy/MM/dd HH:mm:ss&quot;); // ??￥?? ?ð??? ??? format
 * String dateString3 = DateUtil.getTime(&quot;HH:mm:ss&quot;); // ?ð??? ??? format
 * Calendar cal = DateUtil.stringToCalendar(&quot;2002/09/12&quot;, &quot;yyyy/MM/dd&quot;); // String --&gt; Calendar
 * Date date = DateUtil.stringToDate(&quot;2002/09/11&quot;, &quot;yyyy/MM/dd&quot;); //String --&gt; Date
 * </pre>
 *
 * </blockquote>
 *
 * @author $Author: administrator $
 * @version $Id: DateUtils.java,v 1.1 2010/07/18 20:58:53 administrator Exp $
 * @since 2006. 3. 3
 */
public class DateUtils {
    /**
     * ???? ?????u???? "yyyyMMddHHmmss"?? time format???? ????
     *
     * @return ???? ?????u???
     */
    public static String getTime() {
        return getTime("yyyyMMddHHmmss");
    }

    /**
     * ???? ??????? "yyyyMMdd"?? time format???? ????
     *
     * @return ???? ?????
     */
    public static String getDate() {
        return getTime("yyyyMMdd");
    }

    /**
     * ???? ?????ð??? ????? time format???? ????
     *
     * @param format time format
     * @return ????? time format?? ???? ?????
     */
    public static String getTime(String format) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(cal.getTime());
    }

    /**
     * Date Object?? ????? ???? String?? ?? String?? time format?? ?????? parse
     *
     * @param dateString ??? time format???ε? String
     * @param format time format
     * @return ????? String???? ?? ??￥?? Date Object
     */
    public static Date stringToDate(String dateString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        return sdf.parse(dateString, pos);
    }

    /**
     * Calendar Object?? ????? ???? String?? ?? String?? time format?? ?????? parse
     *
     * @param dateString ??? time format???ε? String
     * @param format time format
     * @return ????? String???? ?? ??￥?? Calendar Object
     */
    public static Calendar stringToCalendar(String dateString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        Date date = sdf.parse(dateString, pos);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal;
    }

    /**
     * ??? Date Object?? time format?? ?????? String ???
     *
     * @param date ??? ?????? Date Object
     * @param format time format
     * @return ??????? String
     */
    public static String formatDate(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return sdf.format(cal.getTime());
    }

    /**
     * ??? Calendar Object?? time format?? ?????? String ???
     *
     * @param cal ??? ?????? Calendar Object
     * @param format time format
     * @return ??????? String
     */
    public static String formatCalendar(Calendar cal, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(cal.getTime());
    }

    /**
     * ??? ?????? ?????????? ???
     *
     * @param year ??? ????
     */
    public static boolean isLeapYear(int year) {
        if (year % 4 != 0)
            return false;
        if (year % 400 == 0)
            return true;
        return year % 100 != 0;
    }

    /**
     * ??? ???? ??? ???? ?? ????? ???? ?? ???.
     *
     * @param year ??? ????
     * @param month ??? ?? (1 ~ 12)
     * @return ??? ???? ???? ?? ???
     */
    public static int lastDate(int year, int month) {
        int kLastDates[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        if (month > 12 || month < 0)
            month = 0;

        if (month == 2 && isLeapYear(year))
            return kLastDates[month] + 1;
        else
            return kLastDates[month];
    }

    /**
     * ?? ??￥?? ??????? ???
     */
    public static int daysDiff(String earlierDate, String laterDate, String format) {
        if (earlierDate == null || laterDate == null)
            return 0;

        Date d1 = stringToDate(earlierDate, format);
        Date d2 = stringToDate(laterDate, format);

        return (int) ((d2.getTime() - d1.getTime()) / (24 * 60 * 60 * 1000));
    }

    /**
     * 2???? ??￥?? ???? ?? ???. ???????? ?ð??? ???? ?? ???.
     *
     * @return -1 : date1 < date2 0 : date1 = date2 1 : date1 > date2
     */
    public static int compareDate(String date1, String date2, String format) {
        Calendar c1 = stringToCalendar(date1, format);
        Calendar c2 = stringToCalendar(date2, format);

        return compareDate(c1, c2);
    }

    /**
     * 2???? ??￥?? ???? ?? ???.
     *
     * @return -1 : date1 < date2 0 : date1 = date2 1 : date1 > date2
     */
    public static int compareDate(Date date1, Date date2) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date2);

        return compareDate(c1, c2);
    }

    /**
     * 2???? ??￥?? ???? ?? ???.
     *
     * @return -1 : cal1 < cal2 0 : cal1 = cal2 1 : cal1 > cal2
     */
    public static int compareDate(Calendar cal1, Calendar cal2) {
        int value = 9;

        if (cal1.before(cal2)) {
            value = -1;
        }
        if (cal1.after(cal2)) {
            value = 1;
        }
        if (cal1.equals(cal2)) {
            value = 0;
        }
        return value;
    }

    /**
     * ??? ??￥?? ?????? ?????? ?? ??? ??????.
     *
     * @param startDate - ???? ??￥
     * @param years - ?????? ?? ????. ???? ??￥???? ???? ?????? ???? ???? ???? ??´?.
     */
    public static java.sql.Date rollYears(java.util.Date startDate, int years) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(startDate);
        gc.add(Calendar.YEAR, years);
        return new java.sql.Date(gc.getTime().getTime());
    }

    /**
     * ??? ??￥?? ???? ?????? ?? ??? ??????.
     *
     * @param startDate - ???? ??￥
     * @param months - ?????? ?? ?????. ???? ??￥???? ???? ?????? ???? ???? ???? ??´?.
     */
    public static java.sql.Date rollMonths(java.util.Date startDate, int months) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(startDate);
        gc.add(Calendar.MONTH, months);
        return new java.sql.Date(gc.getTime().getTime());
    }

    /**
     * ??? ??￥?? ???? ?????? ?? ??? ??????.
     *
     * @param startDate - ???? ??￥
     * @param days - ?????? ?? ???. ???? ??￥???? ???? ?????? ???? ???? ???? ??´?.
     */
    public static java.sql.Date rollDays(java.util.Date startDate, int days) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(startDate);
        gc.add(Calendar.DATE, days);
        return new java.sql.Date(gc.getTime().getTime());
    }

    /**
     * ???? ??￥?? yyyyMMdd ??????? ??´?.
     *
     * @return String
     */
    public static String getTomorrow() {
        return getDate(1, "yyyyMMdd");
    }

    /**
     * ???? ??￥?? ?????? ??????? ??´?.
     *
     * @param format ??￥ ????? ???
     * @return String
     */
    public static String getTomorrow(String format) {
        return getDate(1, format);
    }

    /**
     * ???? ??￥?? yyyyMMdd ??????? ??´?.
     *
     * @return String
     */
    public static String getYesterday() {
        return getDate(-1, "yyyyMMdd");
    }

    /**
     * ???? ??￥?? ?????? ??????? ??´?.
     *
     * @param format ??￥ ????? ???
     * @return String
     */
    public static String getYesterday(String format) {
        return getDate(-1, format);
    }

    /**
     * ???? ??￥?? ??? ???? ?????? ?? ??? yyyyMMdd ??????? ??????.
     *
     * @param days ?????? ?? ?? ??. ???u??? ???? ?????? ???? ???? ??´?.
     * @return String
     */
    public static String getDate(int days) {
        return getDate(days, "yyyyMMdd");
    }

    /**
     * ???? ??￥?? ??? ???? ?????? ?? ??? ?????? ??????? ??????.
     *
     * @param days ?????? ?? ?? ??. ???u??? ???? ?????? ???? ???? ??´?.
     * @param format ??￥ ????? ???
     * @return String
     */
    public static String getDate(int days, String format) {
        GregorianCalendar gc = new GregorianCalendar();
        SimpleTimeZone kstZone = new SimpleTimeZone(9 * 60 * 60 * 1000, "Asia/Seoul");
        gc.setTimeZone(kstZone);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        gc.add(Calendar.DATE, days);

        return sdf.format(gc.getTime());
    }

    /**
     * ???? String ('YYYYMMDDHH24MISS')?? formate?? ?°? ??? YYYY?? 1900???? MM?? 12?????? ???. ??) src : 20011213134532 format :
     * "YYYY?? MM?? DD?? HH24:MI:SS" -> 2001?? 12?? 13?? 13:45:32
     *
     * @author ?μ???
     * @param str ?????? ?????
     * @param format ??????
     * @return ????? ?????
     */
    public static String dateFilter(String src, String format) {
        if (src == null || src.length() < 14 || (format.length() < 2))
            return "";

        String str_ret = "";
        int iyyyy, iyy, imm, idd, i24hh, ihh, imi, iss;

        iyyyy = Integer.parseInt(src.substring(0, 4));
        iyy = Integer.parseInt(src.substring(2, 4));
        imm = Integer.parseInt(src.substring(4, 6));
        idd = Integer.parseInt(src.substring(6, 8));
        i24hh = Integer.parseInt(src.substring(8, 10));
        if (i24hh > 12)
            ihh = i24hh - 12;
        else
            ihh = i24hh;
        imi = Integer.parseInt(src.substring(10, 12));
        iss = Integer.parseInt(src.substring(12, 14));

        // YYYY-MM-DD 12??25??13??
        str_ret = replaceString(format, "YYYY", intToString(iyyyy));
        str_ret = replaceString(str_ret, "YY", intToString(iyy));
        str_ret = replaceString(str_ret, "MM", intToString(imm));
        str_ret = replaceString(str_ret, "DD", intToString(idd));
        str_ret = replaceString(str_ret, "HH24", intToString(i24hh));
        str_ret = replaceString(str_ret, "HH", intToString(ihh));
        str_ret = replaceString(str_ret, "MI", intToString(imi));
        str_ret = replaceString(str_ret, "SS", intToString(iss));

        return str_ret;
    }

    /**
     * ???? String ('YYYYMMDDHH24MISS')?? formate?? ?°? ??? YYYY?? 1900???? MM?? 12?????? ???. ??) src : 20011213134532 format :
     * "YYYY?? MM?? DD?? HH24:MI:SS" -> 2001?? 12?? 13?? 13:45:32
     *
     * @author ?μ???(update ????? - 2003/06/02)
     * @param str ?????? ?????
     * @param format ??????
     * @param zeroFG (??,??,??,?? ??)???????? ??? 0?? ?????? ????(true: ????, false:?????)
     * @return ????? ?????
     */
    public static String dateFilter(String src, String format, boolean zeroFG) {
        if (src == null || src.length() < 14 || (format.length() < 2))
            return "";

        String str_ret = "";
        int iyyyy, iyy, imm, idd, i24hh, ihh, imi, iss, temphh;
        String strhh = "";

        if (zeroFG) { // ????? ??? 0?? ????
            temphh = Integer.parseInt(src.substring(8, 10)); // ?ð?(?????)

            if (temphh > 12)
                ihh = temphh - 12;
            else
                ihh = temphh;

            strhh = intToString(ihh);
            if (strhh.length() <= 1)
                strhh = "0" + strhh;

            str_ret = replaceString(format, "YYYY", src.substring(0, 4));
            str_ret = replaceString(str_ret, "YY", src.substring(2, 4));
            str_ret = replaceString(str_ret, "MM", src.substring(4, 6));
            str_ret = replaceString(str_ret, "DD", src.substring(6, 8));
            str_ret = replaceString(str_ret, "HH24", src.substring(8, 10));
            str_ret = replaceString(str_ret, "HH", strhh);
            str_ret = replaceString(str_ret, "MI", src.substring(10, 12));
            str_ret = replaceString(str_ret, "SS", src.substring(12, 14));

        } else { // ????? ??? 0 ?????? ????

            iyyyy = Integer.parseInt(src.substring(0, 4)); // ??
            iyy = Integer.parseInt(src.substring(2, 4)); // ??(?????)
            imm = Integer.parseInt(src.substring(4, 6)); // ??
            idd = Integer.parseInt(src.substring(6, 8)); // ??
            i24hh = Integer.parseInt(src.substring(8, 10)); // ?ð?

            if (i24hh > 12)
                ihh = i24hh - 12;
            else
                ihh = i24hh;

            imi = Integer.parseInt(src.substring(10, 12)); // ??
            iss = Integer.parseInt(src.substring(12, 14)); // ??

            str_ret = replaceString(format, "YYYY", intToString(iyyyy));
            str_ret = replaceString(str_ret, "YY", intToString(iyy));
            str_ret = replaceString(str_ret, "MM", intToString(imm));
            str_ret = replaceString(str_ret, "DD", intToString(idd));
            str_ret = replaceString(str_ret, "HH24", intToString(i24hh));
            str_ret = replaceString(str_ret, "HH", intToString(ihh));
            str_ret = replaceString(str_ret, "MI", intToString(imi));
            str_ret = replaceString(str_ret, "SS", intToString(iss));
        }
        return str_ret;
    }

    private static String intToString(int i) {
        return (new Integer(i)).toString();
    }

    private static String replaceString(String src, String from, String to) {
        StringBuffer res_Buff = new StringBuffer();
        int pos = -1;

        if (src == null || from == null || from.equals(""))
            return src;
        if (to == null)
            to = "";

        while (true) {
            if ((pos = src.indexOf(from)) == -1) {
                res_Buff.append(src);
                break;
            }
            res_Buff.append(src.substring(0, pos)).append(to);
            src = src.substring(pos + from.length());
        }
        return res_Buff.toString();
    }

    // ?и??????? ?? ?????? ???

    public static long getTimeInMillis() {
        GregorianCalendar gc = new GregorianCalendar();
        SimpleTimeZone kstZone = new SimpleTimeZone(9 * 60 * 60 * 1000, "Asia/Seoul");
        gc.setTimeZone(kstZone);
        return gc.getTimeInMillis();
    }

    // java.util.Date ?? ?????? ???

    public static Date getDateObject() {
        GregorianCalendar gc = new GregorianCalendar();
        SimpleTimeZone kstZone = new SimpleTimeZone(9 * 60 * 60 * 1000, "Asia/Seoul");
        gc.setTimeZone(kstZone);
        return gc.getTime();
    }

    /**
     * ??????? ?????? ????? ??? ??￥?? ?????????? ??????. ???? ??? 1?? ??????? 2007?? 1?? 1??, 2?? ??????? 2007?? 5?? 1??, 3?? ??????? 2007?? 3?? 1????? ?? ?????
     * true?? ???????. ???, 3?? ??????? 2007?? 5?? 10???? ??? false?? ??????.
     *
     * @param startDate ??????
     * @param endDate ??????
     * @param testDate ??? ?????
     * @return
     */
    public static boolean isBeetweenDate(Date startDate, Date endDate, Date testDate) {
        boolean result = false;
        if (DateUtils.compareDate(startDate, testDate) == -1) {
            if (DateUtils.compareDate(endDate, testDate) == 1) {
                result = true;
            }
        }

        return result;
    }

       /**********************************************************************
      * ?? ?? : ???? ??￥?? yyyyMMdd ??????? ??????.
     * @param       None
     * @return          String yyyyMMdd ????? ????￥
     * @exception          LException
      **********************************************************************/
    public static String getCurrentDateString() throws Exception {
        return getCurrentDateString("yyyyMMdd");
    }

    /**********************************************************************
      * ?? ?? : ???? ?ð???  HHmmss ??????? ??????.
     * @param       None
     * @return          HHmmss ????? ???? ?ð?
     * @exception          Exception
      **********************************************************************/
    public static String getCurrentTimeString() throws Exception {
        return getCurrentDateString("HHmmss");
    }

    /**********************************************************************
      * ?? ?? : ????￥?? ????? pattern ?? ??? ??????.
     * @param       pattern   SimpleDateFormat ?? ????? pattern
     * @return          String pattern   ????? ????￥
     * @exception          Exception
      **********************************************************************/
    public static String getCurrentDateString(String pattern)
        throws Exception {
        return convertToString(getCurrentTimeStamp(), pattern);
    }

    /**********************************************************************
      * ?? ?? : yyyyMMdd ????? ??￥?? yyyy-MM-dd ??????? ??????.
     * @param       dateData     yyyyMMdd ????? ??￥
     * @return          String yyyy-MM-dd   ????? ??? ??￥
     * @exception          Exception
      **********************************************************************/
    public static String convertFormat(String dateData)
        throws Exception {
        if (dateData == null || (dateData != null && dateData.equals("00000000")) ) {
            return "";
        } else {
            return convertFormat(dateData, "yyyy.MM.dd");
        }
    }

    /**********************************************************************
      * ?? ?? : yyyyMMdd ????? ??￥?? yyyy-MM-dd ??????? ??????.
     * @param       dateData     yyyyMMdd ????? ??￥
     * @return          String yyyy-MM-dd   ????? ??? ??￥
     * @exception          Exception
      **********************************************************************/
    public static String convertFormat(String dateData, String format)
        throws Exception {
        if (dateData == null || (dateData != null && dateData.equals("00000000")) ) {
            return "";
        } else {
            return convertToString(convertToTimestamp(dateData), format);
        }
    }

    /**********************************************************************
      * ?? ?? : yyyyMMdd ????? ??￥?? yyyy-MM-dd ??????? ??????.
     * @param       None
     * @return          Timestamp ???? Timestamp ??
     * @exception          Exception
      **********************************************************************/
    public static Timestamp getCurrentTimeStamp() throws Exception {
        try {
            Calendar cal = new GregorianCalendar();
            Timestamp result = new Timestamp(cal.getTime().getTime());

            return result;
        } catch (Exception e) {
            throw new Exception("[DateUtil][getCurrentTimeStamp]" +
                e.getMessage(), e);
        }
    }

    /**********************************************************************
      * ?? ?? : yyyyMMdd ????? ??￥?? yyyy-MM-dd ??????? ??????.
     * @param       dateData   Timestamp ????? ??￥
     * @return          String yyyy-MM-dd ????? Timestamp ??￥
     * @exception          Exception
      **********************************************************************/
    public static String convertToString(Timestamp dateData)
        throws Exception {
        return convertToString(dateData, "yyyy.MM.dd");
    }

    /**********************************************************************
      * ?? ?? : yyyyMMdd ????? Timestamp ??￥?? pattern ?? ?? ??????? ??????.
     * @param       dateData   Timestamp ????? ??￥
     * @param       pattern   SimpleDateFormat ?? ????? pattern
     * @return             String yyyy/MM/dd ????? Timestamp ??￥
     * @exception         None
      **********************************************************************/
    public static String convertToString(Timestamp dateData, String pattern)
        throws Exception {
        return convertToString(dateData, pattern, java.util.Locale.KOREA);
    }

    /**********************************************************************
      * ?? ?? : yyyyMMdd ????? Timestamp ??￥?? pattern ?? locale  ?? ?? ??????? ??????.
     * @param       dateData   Timestamp ????? ??￥
     * @param       pattern   SimpleDateFormat ?? ????? pattern
     * @param       locale    ?????? LOCALE
     * @return             String pattern ????? Timestamp ??￥
     * @exception         Exception
      **********************************************************************/
    public static String convertToString(Timestamp dateData, String pattern,
        java.util.Locale locale) throws Exception {
        try {
            if (dateData == null) {
                return "";
            }

            SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale);

            //formatter.applyPattern( pattern );
            return formatter.format(dateData);
        } catch (Exception e) {
            throw new Exception("[DateUtil][convertToString]" +
                e.getMessage(), e);
        }
    }

    /**********************************************************************
      * ?? ?? : yyyyMMdd ?????  ??￥?? Timestamp ??  ??????.
     * @param       dateData     yyyyMMdd ????? ??￥
     * @return             Timestamp ????? ??? ??￥
     * @exception         Exception
      **********************************************************************/
    public static Timestamp convertToTimestamp(String dateData)
        throws Exception {
        try {
            if (dateData == null) {
                return null;
            }

            if (dateData.trim().equals("")) {
                return null;
            }

            int dateObjLength = dateData.length();

            String yearString = "2002";
            String monthString = "01";
            String dayString = "01";

            if (dateObjLength >= 4) {
                yearString = dateData.substring(0, 4);
            }

            if (dateObjLength >= 6) {
                monthString = dateData.substring(4, 6);
            }

            if (dateObjLength >= 8) {
                dayString = dateData.substring(6, 8);
            }

            int year = Integer.parseInt(yearString);
            int month = Integer.parseInt(monthString) - 1;
            int day = Integer.parseInt(dayString);

            Calendar cal = new GregorianCalendar();
            cal.set(year, month, day);

            //cal.getTime();
            return new Timestamp(cal.getTime().getTime());
        } catch (Exception e) {
            throw new Exception("[DateUtil][convertToTimestamp]" +
                e.getMessage(), e);
        }
    }

    /**********************************************************************
      * ?? ?? : yyyyMMddHHmmss ?????  ??￥?ð??? Timestamp ??  ??????.
     * @param       dateData   yyyyMMddHHmmss ????? ??￥?ð?
     * @return             Timestamp ????? ??? ??￥?ð?
     * @exception         Exception
      **********************************************************************/
    public static Timestamp convertToTimestampHMS(String dateData)
        throws Exception {
        try {
            if (dateData == null) {
                return null;
            }

            if (dateData.trim().equals("")) {
                return null;
            }

            String yearString = dateData.substring(0, 4);
            String monthString = dateData.substring(4, 6);
            String dayString = dateData.substring(6, 8);
            String hourString = dateData.substring(8, 10);
            String minString = dateData.substring(10, 12);
            String secString = dateData.substring(12, 14);

            int year = Integer.parseInt(yearString);
            int month = Integer.parseInt(monthString) - 1;
            int day = Integer.parseInt(dayString);
            int hour = Integer.parseInt(hourString);
            int min = Integer.parseInt(minString);
            int sec = Integer.parseInt(secString);

            Calendar cal = new GregorianCalendar();
            cal.set(year, month, day, hour, min, sec);

            return new Timestamp(cal.getTime().getTime());
        } catch (Exception e) {
            throw new Exception("[DateUtil][convertToTimestampHMS]" +
                e.getMessage(), e);
        }
    }

    //-----------------------------------java Util ???----------------------------------------//

    /**
    * check date string validation with the default format "yyyyMMdd".
    * @param s date string you want to check with default format "yyyyMMdd".
    * @return date java.util.Date
    */
    private static java.util.Date check(String s)
        throws java.text.ParseException {
        return check(s, "yyyyMMdd");
    }

    /**
     * check date string validation with an user defined format.
     * @param s date string you want to check.
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return date java.util.Date
     */
    private static java.util.Date check(String s, String format)
        throws java.text.ParseException {
        if (s == null) {
            throw new java.text.ParseException("date string to check is null", 0);
        }

        if (format == null) {
            throw new java.text.ParseException("format string to check date is null",
                0);
        }

        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format,
                java.util.Locale.KOREA);
        java.util.Date date = null;

        try {
            date = formatter.parse(s);
        } catch (java.text.ParseException e) {
            /*
            throw new java.text.ParseException(
                    e.getMessage() + " with format \"" + format + "\"",
                    e.getErrorOffset()
            );
            */
            throw new java.text.ParseException(" wrong date:\"" + s +
                "\" with format \"" + format + "\"", 0);
        }

        if (!formatter.format(date).equals(s)) {
            throw new java.text.ParseException("Out of bound date:\"" + s +
                "\" with format \"" + format + "\"", 0);
        }

        return date;
    }

    /**
     * check date string validation with the default format "yyyyMMdd".
     * @param s date string you want to check with default format "yyyyMMdd"
     * @return boolean true ??￥ ????? ?°?, ??????? ??￥?? ??
     *                 false ??￥ ????? ???? ????, ???????? ??? ??￥?? ??
     * @exception         Exception
     */
    public static boolean isValid(String s) throws Exception {
        return DateUtils.isValid(s, "yyyyMMdd");
    }

    /**
     * check date string validation with an user defined format.
     * @param s date string you want to check.
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return boolean true ??￥ ????? ?°?, ??????? ??￥?? ??
     *                 false ??￥ ????? ???? ????, ???????? ??? ??￥?? ??
     * @exception         Exception
     */
    public static boolean isValid(String s, String format)
        throws Exception {
        /*
                        if ( s == null )
                                throw new NullPointerException("date string to check is null");
                        if ( format == null )
                                throw new NullPointerException("format string to check date is null");
        */
        try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format,
                    java.util.Locale.KOREA);
            java.util.Date date = null;

            try {
                date = formatter.parse(s);
            } catch (java.text.ParseException e) {
                return false;
            }

            if (!formatter.format(date).equals(s)) {
                return false;
            }

            return true;
        } catch (Exception e) {
            throw new Exception("[DateUtil][isValid]" + e.getMessage(), e);
        }
    }

    /**
     * return days between two date strings with default defined format.(yyyyMMdd)
     * @param s date string you want to check.
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? ?????? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     *          0: ????? (java.util.Calendar.SUNDAY ?? ??)
     *          1: ????? (java.util.Calendar.MONDAY ?? ??)
     *          2: ????? (java.util.Calendar.TUESDAY ?? ??)
     *          3: ?????? (java.util.Calendar.WENDESDAY ?? ??)
     *          4: ????? (java.util.Calendar.THURSDAY ?? ??)
     *          5: ????? (java.util.Calendar.FRIDAY ?? ??)
     *          6: ????? (java.util.Calendar.SATURDAY ?? ??)
     * ??) String s = "20000529";
     *  int dayOfWeek = whichDay(s, format);
     *  if (dayOfWeek == java.util.Calendar.MONDAY)
     *      System.out.println(" ?????: " + dayOfWeek);
     *  if (dayOfWeek == java.util.Calendar.TUESDAY)
     *      System.out.println(" ?????: " + dayOfWeek);
     * @exception         Exception
     */
    public static int whichDay(String s) throws Exception {
        return whichDay(s, "yyyyMMdd");
    }

    /**
     * return days between two date strings with user defined format.
     * @param s date string you want to check.
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? ?????? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     *          0: ????? (java.util.Calendar.SUNDAY ?? ??)
     *          1: ????? (java.util.Calendar.MONDAY ?? ??)
     *          2: ????? (java.util.Calendar.TUESDAY ?? ??)
     *          3: ?????? (java.util.Calendar.WENDESDAY ?? ??)
     *          4: ????? (java.util.Calendar.THURSDAY ?? ??)
     *          5: ????? (java.util.Calendar.FRIDAY ?? ??)
     *          6: ????? (java.util.Calendar.SATURDAY ?? ??)
     * ??) String s = "2000-05-29";
     *  int dayOfWeek = whichDay(s, "yyyy-MM-dd");
     *  if (dayOfWeek == java.util.Calendar.MONDAY)
     *      System.out.println(" ?????: " + dayOfWeek);
     *  if (dayOfWeek == java.util.Calendar.TUESDAY)
     *      System.out.println(" ?????: " + dayOfWeek);
     * @exception         Exception
     */
    public static int whichDay(String s, String format)
        throws Exception {
        try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format,
                    java.util.Locale.KOREA);
            java.util.Date date = check(s, format);

            java.util.Calendar calendar = formatter.getCalendar();
            calendar.setTime(date);

            return calendar.get(java.util.Calendar.DAY_OF_WEEK);
        } catch (Exception e) {
            throw new Exception("[DateUtil][whichDay]" + e.getMessage(), e);
        }
    }

    /**
     * return days between two date strings with default defined format.("yyyyMMdd")
     * @param String from date string
     * @param String to date string
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? 2?? ???? ?????? ???? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static int daysBetween(String from, String to)
        throws Exception {
        return daysBetween(from, to, "yyyyMMdd");
    }

    /**
     * return days between two date strings with user defined format.
     * @param String from date string
     * @param String to date string
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? 2?? ???? ?????? ???? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static int daysBetween(String from, String to, String format)
        throws Exception {
        // java.text.SimpleDateFormat formatter =
        // new java.text.SimpleDateFormat (format, java.util.Locale.KOREA);
        try {
            java.util.Date d1 = check(from, format);
            java.util.Date d2 = check(to, format);

            long duration = d2.getTime() - d1.getTime();

            return (int) (duration / (1000 * 60 * 60 * 24));

            // seconds in 1 day
        } catch (Exception e) {
            throw new Exception("[DateUtil][daysBetween]" + e.getMessage(), e);
        }
    }

    /**
     * return years between two date strings with default defined format.("yyyyMMdd")
     * @param String from date string
     * @param String to date string
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? 2?? ???? ?????? ???? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static int yearsBetween(String from, String to)
        throws Exception {
        return yearsBetween(from, to, "yyyyMMdd");
    }

    /**
     * return years between two date strings with user defined format.
     * @param String from date string
     * @param String to date string
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? 2?? ???? ?????? ???? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static int yearsBetween(String from, String to, String format)
        throws Exception {
        return (int) (daysBetween(from, to, format) / 365);
    }

    /**
     * return add day to date strings
     * @param String date string
     * @param int ???? ???
     * @return String ??￥ ????? ?°?, ??????? ??￥?? ?? ??? ?????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String addDays(String s, int day) throws Exception {
        return addDays(s, day, "yyyyMMdd");
    }

    /**
     * return add day to date strings with user defined format.
     * @param String date string
     * @param String ???? ???
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? ??? ?????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String addDays(String s, int day, String format)
        throws Exception {
        try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format,
                    java.util.Locale.KOREA);
            java.util.Date date = check(s, format);

            date.setTime(date.getTime() + ((long) day * 1000 * 60 * 60 * 24));

            return formatter.format(date);
        } catch (Exception e) {
            throw new Exception("[DateUtil][addDays]" + e.getMessage(), e);
        }
    }

    /**
     * return add month to date strings
     * @param String date string
     * @param int ???? ???
     * @return String ??￥ ????? ?°?, ??????? ??￥?? ?? ??? ?????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String addMonths(String s, int month)
        throws Exception {
        return addMonths(s, month, "yyyyMMdd");
    }

    /**
     * return add month to date strings with user defined format.
     * @param String date string
     * @param int ???? ???
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return String ??￥ ????? ?°?, ??????? ??￥?? ?? ??? ?????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String addMonths(String s, int addMonth, String format)
        throws Exception {
        try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format,
                    java.util.Locale.KOREA);
            java.util.Date date = check(s, format);

            java.text.SimpleDateFormat yearFormat = new java.text.SimpleDateFormat("yyyy",
                    java.util.Locale.KOREA);
            java.text.SimpleDateFormat monthFormat = new java.text.SimpleDateFormat("MM",
                    java.util.Locale.KOREA);
            java.text.SimpleDateFormat dayFormat = new java.text.SimpleDateFormat("dd",
                    java.util.Locale.KOREA);
            int year = Integer.parseInt(yearFormat.format(date));
            int month = Integer.parseInt(monthFormat.format(date));
            int day = Integer.parseInt(dayFormat.format(date));

            month += addMonth;

            if (addMonth > 0) {
                while (month > 12) {
                    month -= 12;
                    year += 1;
                }
            } else {
                while (month <= 0) {
                    month += 12;
                    year -= 1;
                }
            }

            java.text.DecimalFormat fourDf = new java.text.DecimalFormat("0000");
            java.text.DecimalFormat twoDf = new java.text.DecimalFormat("00");
            String tempDate = String.valueOf(fourDf.format(year)) +
                String.valueOf(twoDf.format(month)) +
                String.valueOf(twoDf.format(day));
            java.util.Date targetDate = null;

            try {
                targetDate = check(tempDate, "yyyyMMdd");
            } catch (java.text.ParseException pe) {
                day = lastDay(year, month);
                tempDate = String.valueOf(fourDf.format(year)) +
                    String.valueOf(twoDf.format(month)) +
                    String.valueOf(twoDf.format(day));
                targetDate = check(tempDate, "yyyyMMdd");
            }

            return formatter.format(targetDate);
        } catch (Exception e) {
            throw new Exception("[DateUtil][addMonths]" + e.getMessage(), e);
        }
    }

    /**
     * return add year to date strings
     * @param String s string
     * @param int ???? ???
     * @return String ??￥ ????? ?°?, ??????? ??￥?? ?? ???  ?????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String addYears(String s, int year) throws Exception {
        return addYears(s, year, "yyyyMMdd");
    }

    /**
     * return add year to date strings  with user defined format.
     * @param String date string
     * @param int ???? ???
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return String ??￥ ????? ?°?, ??????? ??￥?? ?? ??? ?????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String addYears(String s, int year, String format)
        throws Exception {
        try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format,
                    java.util.Locale.KOREA);
            java.util.Date date = check(s, format);
            date.setTime(date.getTime() +
                ((long) year * 1000 * 60 * 60 * 24 * (365)));

            return formatter.format(date);
        } catch (Exception e) {
            throw new Exception("[DateUtil][addYears]" + e.getMessage(), e);
        }
    }

    /**
     * return months between two date strings
     * @param String from date string
     * @param String to date string
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? 2?? ???? ?????? ?????  ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static int monthsBetween(String from, String to)
        throws Exception {
        return monthsBetween(from, to, "yyyyMMdd");
    }

    /**
     * return months between two date strings with user defined format.
     * @param String from date string
     * @param String to date string
     * @return int ??￥ ????? ?°?, ??????? ??￥?? ?? 2?? ???? ??????????  ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static int monthsBetween(String from, String to, String format)
        throws Exception {
        //java.text.SimpleDateFormat formatter =
        //    new java.text.SimpleDateFormat (format, java.util.Locale.KOREA);
        try {
            java.util.Date fromDate = check(from, format);
            java.util.Date toDate = check(to, format);

            // if two date are same, return 0.
            if (fromDate.compareTo(toDate) == 0) {
                return 0;
            }

            java.text.SimpleDateFormat yearFormat = new java.text.SimpleDateFormat("yyyy",
                    java.util.Locale.KOREA);
            java.text.SimpleDateFormat monthFormat = new java.text.SimpleDateFormat("MM",
                    java.util.Locale.KOREA);
            java.text.SimpleDateFormat dayFormat = new java.text.SimpleDateFormat("dd",
                    java.util.Locale.KOREA);

            int fromYear = Integer.parseInt(yearFormat.format(fromDate));
            int toYear = Integer.parseInt(yearFormat.format(toDate));
            int fromMonth = Integer.parseInt(monthFormat.format(fromDate));
            int toMonth = Integer.parseInt(monthFormat.format(toDate));
            int fromDay = Integer.parseInt(dayFormat.format(fromDate));
            int toDay = Integer.parseInt(dayFormat.format(toDate));

            int result = 0;
            result += ((toYear - fromYear) * 12);
            result += (toMonth - fromMonth);

            //        if (((toDay - fromDay) < 0) ) result += fromDate.compareTo(toDate);
            // ceil?? floor?? ???
            if (((toDay - fromDay) > 0)) {
                result += toDate.compareTo(fromDate);
            }

            return result;
        } catch (Exception e) {
            throw new Exception("[DateUtil][monthsBetween]" +
                e.getMessage(), e);
        }
    }

    /**
     *  ????? ?????? ???? ????
     * @param String src string
     * @return String ??￥ ????? ?°?, ??????? ??￥?? ?? ????? ?????? ???? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String lastDayOfMonth(String src) throws Exception {
        return lastDayOfMonth(src, "yyyyMMdd");
    }

    /**
     *  ????? ?????? ???? ????
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return String ??￥ ????? ?°?, ??????? ??￥?? ?? ????? ?????? ???? ????
     *           ????? ??? ????? ???????? ??? ??￥: java.text.ParseException ???
     * @exception         Exception
     */
    public static String lastDayOfMonth(String src, String format)
        throws Exception {
        try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format,
                    java.util.Locale.KOREA);
            java.util.Date date = check(src, format);

            java.text.SimpleDateFormat yearFormat = new java.text.SimpleDateFormat("yyyy",
                    java.util.Locale.KOREA);
            java.text.SimpleDateFormat monthFormat = new java.text.SimpleDateFormat("MM",
                    java.util.Locale.KOREA);

            int year = Integer.parseInt(yearFormat.format(date));
            int month = Integer.parseInt(monthFormat.format(date));
            int day = lastDay(year, month);

            java.text.DecimalFormat fourDf = new java.text.DecimalFormat("0000");
            java.text.DecimalFormat twoDf = new java.text.DecimalFormat("00");
            String tempDate = String.valueOf(fourDf.format(year)) +
                String.valueOf(twoDf.format(month)) +
                String.valueOf(twoDf.format(day));

            java.util.Date targetDate = check(tempDate, "yyyyMMdd");

            return formatter.format(targetDate);
        } catch (Exception e) {
            throw new Exception("[DateUtil][lastDayOfMonth]" +
                e.getMessage(), e);
        }
    }

    private static int lastDay(int year, int month)
        throws java.text.ParseException {
        int day = 0;

        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day = 31;

            break;

        case 2:

            if ((year % 4) == 0) {
                if (((year % 100) == 0) && ((year % 400) != 0)) {
                    day = 28;
                } else {
                    day = 29;
                }
            } else {
                day = 28;
            }

            break;

        default:
            day = 30;
        }

        return day;
    }

    //???? ???

    /**********************************************************************
      * ?? ?? : ??¹??? ???????? ????? ??????? ????????.
     * @param datestr
     * @return ?????? ?????
      **********************************************************************/
    public static String getYearMonthDateString(String datestr) {
        String datestring = "";

        if ((datestr == null) || datestr.trim().equals("")) {
            datestring = "";
        } else if (datestr.trim().length() < 6) {
            datestring = datestr;
        } else if (datestr.length() >= 6) {
            datestring = new StringBuffer(datestr.substring(0, 4)).append("-")
                                                                  .append(datestr.substring(
                        4, 6)).toString();
        }

        return datestring;
    }

    /**
    * ???? : ???? ?ð??? ???? ?ð? ?????? ????? ??????? ??????.
    * @param s1
    * @param s2
    * @return
    */
    public static boolean isWorkingTime(String s1, String s2) {
        long start = System.currentTimeMillis();
        boolean flag = false;
        int currH = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        int currM = Calendar.getInstance().get(Calendar.MINUTE);

        int startH = Integer.parseInt(s1.substring(0, 2));
        int startM = Integer.parseInt(s1.substring(3, 5));
        int endH = Integer.parseInt(s2.substring(0, 2));
        int endM = Integer.parseInt(s2.substring(3, 5));

        if ((((currH == startH) && (currM >= startM)) || (currH > startH)) &&
                ((currH < endH) || ((currH == endH) && (currM <= endM)))) {
            flag = true;
        }

        return flag;
    }
    /**
	* get system time with a formatter
	* @param String formatter : yyyyMMdd....
	* @return String
	*/
	public static String getCurrentTime(String formatter) {
		SimpleDateFormat fmt = new SimpleDateFormat(formatter);
		fmt.setTimeZone( getTimeZone() );

		return fmt.format(new java.util.Date( System.currentTimeMillis() ));
	}
	/**
	* get default SimpleTimeZone (System Properties)
	* @return SimpleTimeZone
	*/
	public static TimeZone getTimeZone() {
		return TimeZone.getDefault();
	}
	/**
	* get default time zone ID (System Properties)
	* @return String
	*/
	public static String getTimeZoneID() {
		return ( TimeZone.getDefault() ).getID();
	}

}
